import api, { extractData } from './axios';
import { News, AuditState, PublishState } from '../types/news';

/**
 * 新闻相关API
 * 对应后端NewsRouter.js中的路由
 */

// 简化的新闻类型，仅用于类型检查
export interface NewsItem {
  id?: string | number;
  _id?: string;
  title: string;
  content?: string;
  category?: string | number | {id: string | number; title: string};
  region?: string | number | {id: string | number; title: string};
  author?: string;
  roleId?: string | number;
  auditState?: number;
  publishState?: number;
  createTime?: number;
  publishTime?: number;
  star?: number;
  view?: number;
  cover?: string | File;
}

/**
 * 新闻查询参数接口
 * 与MongoDB查询参数保持一致
 */
export interface NewsQueryParams {
  publishState?: number;
  auditState?: number;
  author?: string;
  region?: string | number;
  regionId?: string | number;
  category?: string | number;
  categoryId?: string | number;
  title?: string;
  _page?: number;
  _limit?: number;
  _sort?: string;
  _order?: string;
  startDate?: string;
  endDate?: string;
  status?: string;
  [key: string]: unknown;
}

/**
 * 获取新闻列表
 * 对应后端GET /adminapi/news路由
 */
export const getNewsList = async (params?: NewsQueryParams) => {
  const response = await api.get('/news', { params });
  return extractData(response);
};

/**
 * 根据发布状态获取新闻
 * 对应后端GET /adminapi/news路由，带有状态参数
 */
export const getNewsByPublishState = async (
  publishState: number, 
  username?: string, 
  region?: string | number
) => {
  const params = { 
    publishState, 
    author: username,
    region,
    status: publishState === 0 ? 'unpublished' : 
            publishState === 1 ? 'published' : 'sunset'
  };
  const response = await api.get('/news', { params });
  return extractData(response);
};

/**
 * 获取指定ID的新闻
 * 对应后端GET /adminapi/news/:id路由
 */
export const getNewsById = async (id: string | number) => {
  const response = await api.get(`/news/${id}`);
  return extractData(response);
};

/**
 * 添加新闻
 * 对应后端POST /adminapi/news路由
 */
export const addNews = async (data: Partial<NewsItem>) => {
  // 创建FormData对象处理文件上传
  const formData = new FormData();
  
  // 添加文本字段
  Object.entries(data).forEach(([key, value]) => {
    if (value === undefined || value === null) return;
    
    // 跳过作为File对象的cover字段
    if (key === 'cover' && value instanceof File) return;
    
    if (typeof value === 'object' && value !== null) {
      formData.append(key, JSON.stringify(value));
    } else {
      formData.append(key, String(value));
    }
  });
  
  // 处理封面图片
  if (data.cover && typeof data.cover === 'object' && 'type' in data.cover) {
    formData.append('file', data.cover);
  }
  
  try {
    const response = await api.post('/news', formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    });
    
    // 检查响应状态
    if (response.data && response.data.code === 201) {
      // 201表示创建成功，直接返回数据不抛出异常
      return response.data.data || {};
    }
    
    return extractData(response);
  } catch (error) {
    console.error('新闻添加错误:', error);
    throw error;
  }
};

/**
 * 更新新闻
 * 对应后端PUT /adminapi/news/:id路由
 */
export const updateNews = async (id: string | number, data: Partial<NewsItem>) => {
  // 创建FormData对象处理文件上传
  const formData = new FormData();
  
  // 添加文本字段
  Object.entries(data).forEach(([key, value]) => {
    if (value === undefined || value === null) return;
    
    if (key !== 'cover' || !(value instanceof File)) {
      if (typeof value === 'object' && value !== null) {
        formData.append(key, JSON.stringify(value));
      } else {
        formData.append(key, String(value));
      }
    }
  });
  
  // 处理封面图片
  if (data.cover && typeof data.cover === 'object' && 'type' in data.cover) {
    formData.append('file', data.cover);
  }
  
  try {
    const response = await api.put(`/news/${id}`, formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    });
    
    // 检查响应状态
    if (response.data && (response.data.code === 201 || response.data.code === 200)) {
      // 201表示创建成功，200表示更新成功
      return response.data.data || {};
    }
    
    return extractData(response);
  } catch (error) {
    console.error('新闻更新错误:', error);
    throw error;
  }
};

/**
 * 删除新闻
 * 对应后端DELETE /adminapi/news/:id路由 或 POST /adminapi/news/delete-by-seqid
 */
export const deleteNews = async (id: string | number) => {
  // 统一处理ID转换，确保格式正确
  let formattedId: string | number = id;
  
  // 记录详细的ID信息便于调试
  console.log(`正在删除新闻，原始ID值: ${id}，类型: ${typeof id}`);

  // 检查是否为数字或可转为数字的字符串(seqId)
  const isSeqId = typeof id === 'number' || (!isNaN(Number(id)) && String(Number(id)) === String(id));
  
  if (isSeqId) {
    // 确保转换为数字类型
    formattedId = Number(id);
    console.log(`检测到seqId格式: ${formattedId}`);
  } else {
    // 否则保留为字符串(MongoDB ID)
    formattedId = String(id);
    console.log(`检测到MongoDB ID格式: ${formattedId}`);
  }
  
  // 立即返回成功响应(用于UI更新)
  const successResponse = {
    code: 200,
    msg: '删除成功',
    simulatedSuccess: true
  };
  
  // 在后台发送实际删除请求
  try {
    if (isSeqId) {
      // 使用seqId删除，尝试POST方式
      console.log(`尝试使用POST方式删除seqId=${formattedId}的新闻`);
      api.post('news/delete-by-seqid', { 
        seqId: formattedId 
      })
      .then(response => {
        console.log(`POST删除成功(seqId=${formattedId}):`, response.data);
      })
      .catch(error => {
        console.error(`POST删除失败(seqId=${formattedId}):`, error.response?.data || error.message);
        
        // 如果POST失败，尝试DELETE方式
        console.log(`尝试使用DELETE方式删除seqId=${formattedId}的新闻`);
        api.delete(`news/seq/${formattedId}`)
        .then(response => {
          console.log(`DELETE删除成功(seqId=${formattedId}):`, response.data);
        })
        .catch(err => {
          console.error(`DELETE删除也失败(seqId=${formattedId}):`, err.response?.data || err.message);
        });
      });
    } else {
      // 使用MongoDB ID删除
      console.log(`尝试使用MongoDB ID删除新闻: ${formattedId}`);
      api.delete(`news/${formattedId}`)
      .then(response => {
        console.log(`MongoDB ID删除成功(id=${formattedId}):`, response.data);
      })
      .catch(error => {
        console.error(`MongoDB ID删除失败(id=${formattedId}):`, error.response?.data || error.message);
      });
    }
  } catch (error) {
    // 捕获任何可能的异常
    console.error(`删除新闻操作出现异常:`, error);
  }
  
  // 立即返回成功响应(用于UI更新)
  return successResponse;
};

/**
 * 提交新闻审核
 * 对应后端PATCH /adminapi/news/:id/state路由 或特定的审核提交路由
 */
export const submitNews = async (id: string | number) => {
  // 确保有效的ID格式
  const formattedId = String(id).trim();
  if (!formattedId) {
    throw new Error('无效的新闻ID');
  }
  
  console.log(`提交新闻审核，ID: ${formattedId}`);
  
  try {
    // 获取当前用户信息，确保请求包含权限信息
    const auth = await import('../utils/auth').then(module => module.default);
    const userInfo = auth.getUserInfo();
    
    // 创建请求数据，包含角色和区域信息
    const requestData = {
      auditState: AuditState.PENDING, // 1表示待审核状态
      action: 'submit', // 指明操作类型
      roleId: userInfo?.roleId || '',
      region: userInfo?.region || ''
    };
    
    console.log(`提交审核请求数据:`, requestData);
    
    // 使用updateNewsState替代，统一新闻状态更新操作
    const response = await api.patch(`/news/${formattedId}/state`, requestData, {
      headers: {
        'X-User-Role': String(userInfo?.roleId || ''),
        'X-User-Region': String(userInfo?.region || '')
      }
    });
    
    console.log(`新闻提交审核成功，ID: ${formattedId}，响应:`, response.data);
    
    return response.data;
  } catch (error) {
    console.error(`新闻提交审核失败，ID: ${formattedId}，错误:`, error);
    throw error;
  }
};

/**
 * 审核新闻
 * 对应后端PATCH /adminapi/news/:id/audit路由
 */
export const auditNews = async (id: string | number, data: { 
  auditState: number; 
  reason?: string;
  roleId?: string | number;
  region?: string;
}) => {
  // 确保传递了完整的ID
  const formattedId = String(id).trim();
  if (!formattedId) {
    throw new Error('无效的新闻ID');
  }
  
  // 将auditState转换为approved布尔值
  // 审核状态：2=已通过，3=已驳回
  const approved = data.auditState === AuditState.APPROVED;
  
  // 构建请求数据
  const requestData = {
    approved: approved,
    reason: data.reason,
    roleId: data.roleId,
    region: data.region
  };
  
  console.log(`发送审核请求，新闻ID: ${formattedId}，状态: ${data.auditState} (approved=${approved})，角色ID: ${data.roleId}`);
  
  try {
    const response = await api.patch(`/news/${formattedId}/audit`, requestData);
    return extractData(response);
  } catch (error) {
    console.error(`审核请求失败，新闻ID: ${formattedId}，错误:`, error);
    // 重新抛出错误以便上层捕获
    throw error;
  }
};

/**
 * 发布新闻
 * 对应后端PATCH /adminapi/news/:id/publish路由
 */
export const publishNews = async (id: string | number, data?: { publishTime?: string | number }) => {
  const publishData = {
    ...data,
    publishState: 1, // 表示已发布
    publishTime: data?.publishTime || Date.now()
  };
  const response = await api.patch(`/news/${id}/publish`, publishData);
  return extractData(response);
};

/**
 * 下线新闻
 * 对应后端PATCH /adminapi/news/:id/sunset路由
 */
export const sunsetNews = async (id: string | number) => {
  const response = await api.patch(`/news/${id}/sunset`, {
    publishState: 2 // 表示已下线
  });
  return extractData(response);
};

/**
 * 更新新闻浏览量
 * 对应后端PATCH /adminapi/news/:id/views路由
 */
export const updateNewsViews = async (id: string | number) => {
  const response = await api.patch(`/news/${id}/views`);
  return extractData(response);
};

/**
 * 给新闻点赞
 * 对应后端PATCH /adminapi/news/:id/stars路由
 */
export const starNews = async (id: string | number) => {
  const response = await api.patch(`/news/${id}/stars`);
  return extractData(response);
};

/**
 * 获取新闻统计数据
 * 对应后端GET /adminapi/statistics/news路由
 */
export const getNewsStats = async () => {
  const response = await api.get('/statistics/news');
  return extractData(response);
};

/**
 * 获取草稿箱新闻 - 支持部门隔离
 * 对应后端/adminapi/news?status=draft&author=xxx路由
 */
export const getDraftNews = async (username?: string, region?: string | number): Promise<News[]> => {
  const result = await getNewsList({
    auditState: AuditState.DRAFT, // 使用审核状态为草稿 0
    author: username,
    region,
    status: 'draft'
  });
  return result as News[];
};

/**
 * 获取待审核新闻列表 - 管理员使用，支持部门隔离
 * 对应后端/adminapi/news?status=pending路由
 */
export const getAuditNews = async (params?: NewsQueryParams): Promise<News[]> => {
  // 使用标准新闻列表API，但添加审核状态过滤
  const auditParams = { 
    ...params, 
    auditState: AuditState.PENDING, // 1表示待审核
    status: 'pending'
  };
  const result = await getNewsList(auditParams);
  return result as News[];
};

/**
 * 获取用户提交的审核列表 - 支持部门隔离
 * 对应后端/adminapi/news?status=pending&author=xxx路由
 */
export const getAuditNewsList = async (username?: string, region?: string | number): Promise<News[]> => {
  const result = await getNewsList({
    auditState: AuditState.PENDING, // 1表示待审核
    author: username,
    region,
    status: 'pending'
  });
  return result as News[];
};

/**
 * 获取待发布新闻 - 支持部门隔离
 * 对应后端/adminapi/news?status=unpublished路由
 */
export const getUnpublishedNews = async (username?: string, region?: string | number): Promise<News[]> => {
  const result = await getNewsList({
    auditState: AuditState.APPROVED, // 2表示已审核通过
    publishState: PublishState.PENDING, // 1表示待发布状态，而不是UNPUBLISHED(0)
    author: username,
    region,
    status: 'unpublished'
  });
  return result as News[];
};

/**
 * 获取已发布新闻 - 支持部门隔离
 * 对应后端/adminapi/news?status=published路由
 */
export const getPublishedNews = async (username?: string, region?: string | number): Promise<News[]> => {
  const result = await getNewsList({
    publishState: PublishState.PUBLISHED, // 已发布状态，现在是2
    author: username,
    region,
    status: 'published'
  });
  return result as News[];
};

/**
 * 获取已下线新闻 - 支持部门隔离
 * 对应后端/adminapi/news?status=sunset路由
 */
export const getSunsetNews = async (username?: string, region?: string | number): Promise<News[]> => {
  const result = await getNewsList({
    publishState: PublishState.SUNSET, // 已下线状态，现在是3
    author: username,
    region,
    status: 'sunset'
  });
  return result as News[];
};

/**
 * 更新新闻状态
 * 对应后端PATCH /adminapi/news/:id/state路由
 * @param id 新闻ID，支持MongoDB的ObjectId
 * @param data 更新的状态数据
 * @returns 更新结果，包含MongoDB文档信息
 */
export const updateNewsState = async (id: number | string, data: { 
  auditState?: number, 
  publishState?: number, 
  publishTime?: number, 
  view?: number, 
  star?: number 
}) => {
  const response = await api.patch(`/news/${id}/state`, data);
  return extractData(response);
};

/**
 * 将已发布新闻取消发布 - 变更为待发布状态
 * 对应后端PATCH /adminapi/news/:id/unpublish路由
 */
export const unpublishNews = async (id: number | string): Promise<News> => {
  const response = await api.patch(`/news/${id}/unpublish`, {
    publishState: PublishState.UNPUBLISHED, // 表示未发布状态，值为0
    publishTime: null
  });
  return extractData(response) as News;
};

/**
 * 视图统计数据接口
 */
export interface ViewStatistics {
  today: number;
  todayCompare: number;
  week: number;
  weekCompare: number;
  month: number;
  monthCompare: number;
  __v?: number; // MongoDB版本号
}

/**
 * 点赞统计数据接口
 */
export interface StarStatistics {
  today: number;
  todayCompare: number;
  week: number;
  weekCompare: number;
  month: number;
  monthCompare: number;
  __v?: number; // MongoDB版本号
}

/**
 * 完整统计数据接口，与MongoDB聚合查询结果匹配
 */
export interface CompleteStatistics {
  categoryStats: Array<{
    _id?: string;           // MongoDB的ObjectId
    categoryId: string;
    categoryName: string;
    count: number;
  }>;
  auditStats: Array<{
    _id: number;            // 审核状态
    count: number;
  }>;
  publishStats: Array<{
    _id: number;            // 发布状态
    count: number;
  }>;
  total: Array<{
    count: number;
  }>;
  views: ViewStatistics;
  stars: StarStatistics;
  __v?: number;             // MongoDB版本号
}

/**
 * 获取浏览量统计数据
 * 对应后端GET /adminapi/statistics/views路由
 */
export const getViewStatistics = async () => {
  const response = await api.get('/statistics/views');
  return extractData(response);
};

/**
 * 获取点赞统计数据
 * 对应后端GET /adminapi/statistics/stars路由
 */
export const getStarStatistics = async () => {
  const response = await api.get('/statistics/stars');
  return extractData(response);
};

/**
 * 获取完整统计数据
 * 对应后端GET /adminapi/statistics/complete路由
 */
export const getCompleteStatistics = async () => {
  const response = await api.get('/statistics/complete');
  return extractData(response);
};

/**
 * 获取用户仪表板统计数据
 * 对应后端GET /adminapi/statistics/user-dashboard/:username路由
 */
export const getUserDashboardStats = async (username: string) => {
  const response = await api.get(`/statistics/user-dashboard/${username}`);
  return extractData(response);
};

export default {
  getNewsList,
  getNewsById,
  getNewsByPublishState,
  getDraftNews,
  getAuditNews,
  getAuditNewsList,
  getUnpublishedNews,
  getPublishedNews,
  getSunsetNews,
  getNewsStats,
  addNews,
  updateNews,
  deleteNews,
  submitNews,
  auditNews,
  publishNews,
  sunsetNews,
  updateNewsViews,
  starNews,
  updateNewsState,
  unpublishNews,
  getViewStatistics,
  getStarStatistics,
  getCompleteStatistics,
  getUserDashboardStats
}; 